<template>
  <!-- 登录 -->
  <el-dialog v-model="loginVisible" width="400px" class="login_dialog" align-center @close="handleCloseDialog">
    <el-tabs v-model="activeName" @tab-click="handleClickTab">
      <el-tab-pane label="二维码登录" name="first">
        <el-alert title="说明" type="warning" description="由于网易云扫码登录接口响应较慢，所需时间大致两分钟左右，建议采用手机号密码登录" show-icon
          style="margin-bottom: 10px;" />
        <div class="sao_code_wrapper">
          <div style="width:160px">
            <img style="width: 100%;"
              src="https://p5.music.126.net/obj/wo3DlcOGw6DClTvDisK1/9643571155/525c/faac/2dc6/fe695c03c7c358ddaa4651736b26a55f.png"
              alt="">
          </div>
          <div class="qr_codes">
            <h3>扫码登录</h3>
            <div class="code_img">
              <img :src=" loginQrCode" alt="">
              <div class="fail_code_mask" v-if="isFail">
                <p>二维码已失效</p>
                <el-button type="primary" @click="refushCode">点击刷新</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="登录" name="second">
        <el-form ref="loginFormRef" :model="loginForm" label-width="70px" :rules="loginRules" status-icon>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号" maxlength="11" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
          </el-form-item>
        </el-form>
        <div class="agree_checkbox">
          <el-checkbox v-model="loginChecked" />同意
          <el-link :underline="false" type="primary" href="https://st.music.163.com/official-terms/service"
            target="_blank">《服务条款》</el-link>
          <el-link :underline="false" type="primary" href="https://st.music.163.com/official-terms/privacy"
            target="_blank">《隐私政策》</el-link>
          <el-link :underline="false" type="primary" href="https://st.music.163.com/official-terms/children"
            target="_blank">《儿童隐私政策》</el-link>
        </div>
        <el-button type="primary" :loading="loginBtnLoading" @click="login(loginFormRef)">登录</el-button>
      </el-tab-pane>
      <!-- <el-tab-pane label="注册" name="third">
        <el-form ref="registerFormRef" :model="registerForm" label-width="70px" :rules="registerRules" status-icon>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="registerForm.nickname" placeholder="昵称不少于4个字母或2个汉字" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model.trim="registerForm.password" maxlength="20"
              placeholder="设置登录密码，不少于8位" />
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="registerForm.captcha" placeholder="请输入验证码">
              <template #append>
                <div class="cursor_class" @click="getCode" v-if="isCode">
                  获取验证码
                </div>
                <div v-else>{{ countdown }}s</div>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="agree_checkbox">
          <el-checkbox v-model="loginChecked" />同意
          <el-link :underline="false" type="primary" href="https://st.music.163.com/official-terms/service"
            target="_blank">《服务条款》</el-link>
          <el-link :underline="false" type="primary" href="https://st.music.163.com/official-terms/privacy"
            target="_blank">《隐私政策》</el-link>
          <el-link :underline="false" type="primary" href="https://st.music.163.com/official-terms/children"
            target="_blank">《儿童隐私政策》</el-link>
        </div>
        <el-button type="primary" @click="register(registerFormRef)">注册</el-button>
      </el-tab-pane> -->
    </el-tabs>
  </el-dialog>
</template>
<script lang="ts" setup>
import * as loginApi from '@/api/login'
import * as registerApi from '@/api/register'
import { ref, reactive, getCurrentInstance } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, TabsPaneContext } from 'element-plus'
import { getInfo } from "@/api/userinfo";
import { useStore } from 'vuex'
const store = useStore()
const { proxy }: any = getCurrentInstance()
const loginVisible = ref(false)
const loginChecked = ref(false)
const activeName = ref('first')
const countdown = ref(60)
const isCode = ref(true)
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const loginBtnLoading = ref(false)
// 二维码是否失效
const isFail = ref(false)
// 二维码key
const qrCodeKey = ref('')
// 二维码base64图片
const loginQrCode = ref('')
const loginForm = reactive({
  phone: '',
  password: '',
})
const registerForm = reactive({
  nickname: '',
  phone: '',
  password: '',
  captcha: '',
})
const codeTime = null
let timer: any = null
defineExpose({
  loginVisible,
  getQrKeyData: () => getQrKeyData()
})
// 昵称校验
const validateNickname = (rule: any, value: any, callback: any) => {
  let reg = /^[\u4e00-\u9fa5]{2,}$|^[a-zA-Z0-9]{4,}$/
  if (!reg.test(value)) {
    callback(new Error('昵称不少于4个字母或2个汉字'))
  }
  callback()
}
// 手机号码校验
const validatePhone = (rule: any, value: any, callback: any) => {
  let reg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if (!reg.test(value)) {
    callback(new Error('请输入正确手机号'))
  }
  callback()
}
// 密码校验
const validatePass = (rule: any, value: any, callback: any) => {
  let reg =
    /^(?!^\d+$)(?!^[A-Za-z]+$)(?!^[^A-Za-z0-9]+$)(?!^.*[\u4E00-\u9FA5].*$)^\S{6,20}$/
  if (!reg.test(value)) {
    callback(new Error('包含字母、数字、符号中至少两种'))
  }
  callback()
}
// 登录校验规则
const loginRules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' },
  ],
  password: [
    {
      required: true,
      message: '请输入登录密码',
      trigger: 'blur',
    },
  ],
})
// 注册校验规则
const registerRules = reactive<FormRules>({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { validator: validateNickname, trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度为8-20位', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' },
  ],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})
//获取验证码
const getCode = async () => {
  let reg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if (!reg.test(registerForm.phone)) {
    ElMessage({
      message: '请输入正确的手机号',
      type: 'error',
      duration: 3000
    })
    return
  }
  try {
    const data: any = await registerApi.check({ phone: registerForm.phone })
    if (data.exist === 1) {
      ElMessage({
        message: '该手机号已注册过',
        type: 'error',
        duration: 3000
      })
      return
    }
    // 发送验证码
    await registerApi.sent({ phone: registerForm.phone })
    // 倒计时
    countdown.value = 60
    isCode.value = false
    proxy.codeTime = setInterval(() => {
      if (countdown.value === 0) {
        isCode.value = true
        clearInterval(proxy.codeTime)
      }
      countdown.value--
    }, 1000)
  } catch (error) {
    console.log(error)
  }
}
const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!loginChecked.value) {
    ElMessage('请先勾选同意《服务条款》、《隐私政策》、《儿童隐私政策》')
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        loginBtnLoading.value = true
        const data: any = await loginApi.login(loginForm)
        localStorage.setItem('cookie', data.cookie)
        getUserInfoData()
      } catch (error:any) {
        console.log(error)
        ElMessage({
          message: error.message,
          type: 'error',
          duration: 5000
        })
      } finally {
        loginBtnLoading.value = false
        loginVisible.value = false
      }
    }
  })
}
const register = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!loginChecked.value) {
    ElMessage('请先勾选同意《服务条款》、《隐私政策》、《儿童隐私政策》')
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 验证验证码
        await registerApi.verify({ phone: registerForm.phone, captcha: registerForm.captcha })
        // 注册
        await registerApi.cellphone(registerForm)
        ElMessage({
          message: '注册成功',
          type: 'success',
        })
        activeName.value = "first"
      } catch (error) {
        console.log(error)
      }
    }
  })
}
// tab 被选中时触发
const handleClickTab = (pane: TabsPaneContext, ev: Event) => {
  if (pane.props.name === 'first') {
    getQrKeyData()
  } else {
    clearInterval(timer);
  }
}
// 获取二维码key
const getQrKeyData = async () => {
  let nowtime = new Date().getTime()
  const { data }: { data: any } = await loginApi.getQrKey({
    timestamp: nowtime
  })
  qrCodeKey.value = data.unikey
  const res: any = await loginApi.getQrcreate({
    key: qrCodeKey.value,
    qrimg: true,
    timestamp: new Date().getTime()
  })
  loginQrCode.value = res.data.qrimg
  // 轮询检测二维码状态
  checkQrCodeStatus()
}
// 检测二维码状态
const checkQrCodeStatus = () => {
  let nowtime2 = new Date().getTime()
  timer = setInterval(async () => {
    const res: any = await loginApi.getQrcheck({
      key: qrCodeKey.value,
      timestamp: nowtime2
    })
    console.log(res.code);
    if (res.code === 803) {
      console.log('进来了');
      localStorage.setItem('cookie', res.cookie)
      getUserInfoData()
      loginVisible.value = false
      clearInterval(timer)
    }
    if (res.code === 800) {
      isFail.value = true
      clearInterval(timer)
    }
  }, 3000)
}
// 根据cookie获取用户信息
const getUserInfoData = async () => {
  store.commit('SET_ISLOGIN', true)
  // if (localStorage.getItem('cookie')) {
  //   const res: any = await getInfo({ cookie: localStorage.getItem('cookie') })
  //   localStorage.setItem("userInfo", JSON.stringify(res.profile))
  //   userInfo.value = proxy.$getUserInfo()
  // }
  // location.reload() // 强制刷新让navbar读取userInfo信息
}
// 刷新二维码
const refushCode = () => {
  isFail.value = false
  getQrKeyData()
}
// 关闭登录对话框
const handleCloseDialog = () => {
  clearInterval(timer);
  activeName.value = 'first'
  // 清空表单
  loginForm.phone = ''
  loginForm.password = ''
  registerForm.nickname = ''
  registerForm.phone = ''
  registerForm.password = ''
  registerForm.captcha = ''
}
</script>
<style lang="scss" scoped>
.login_dialog {
  min-width: 300px;

  .agree_checkbox {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .el-checkbox {
      margin-right: 5px;
    }
  }

  .el-button {
    width: 100%;
    margin-top: 20px;
  }
}
.sao_code_wrapper {
  display: flex;
  align-items: center;

  .qr_codes {
    display: flex;
    justify-content: center;
    margin-left: 10px;
    flex-direction: column;
    align-items: center;

    .code_img {
      position: relative;
      width: 180px;
      height: 180px;

      img {
        width: 100%;
        height: 100%;
      }

      .fail_code_mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.9);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        button {
          width: 50%;
          margin-top: 0;
        }
      }
    }
  }
}

:deep(.el-dialog__body) {
  padding: 10px 20px 30px 20px;
}
</style>